const jwt = require('jsonwebtoken');
module.exports = class extends baseRouter {
    constructor() {
        super();
        this.nameSpace = "/manage-api";
        this.webTools=require("../../common/module/webtools");
        this.curUserInfo = require('../../common/func/cur-user-info').init();
        this.UrlList = ['/user/login', '/system/custom-theme/login-page/getItemBySign']; //白名单
    }

    static init() {
        return new this();
    }
    GetRouter(app) {
        let self=this;
        app.use(this.nameSpace, function (req, res, next) {
            res.header('Access-Control-Allow-Origin', '*');
            res.setHeader('Access-Control-Allow-Credentials', true); //告诉客户端可以在HTTP请求中带上Cookie
            res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild , UserID , UserOrgStructID,MT,VK');
            res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
            if (req.method === 'OPTIONS') {
                res.send(200);
            } else {
                next();
            }
        });

        //接口鉴权
        app.use(this.nameSpace,  (req, res, next)=> {
            let isPass = false;

            this.UrlList.forEach((item) => {
                if (item.toLocaleLowerCase() === req.path.toLocaleLowerCase()) {
                    isPass = true;
                }
            });
            if (isPass) {
                next();
                return;
            }

            let VK = req.headers["vk"];
            let MT = req.headers["mt"];
            let ParamList = [];
            if (req.method === "POST") {
                for (let key in req.body) {
                    if (req.body[key] != undefined) {
                        let up = {
                            key: key.toLocaleLowerCase(),
                            value: req.body[key]
                        };
                        ParamList.push(up);
                    }


                }
            }
            if (req.method === "GET") {
                for (let key in req.query) {
                    if (req.query[key] != undefined) {
                        let up = {
                            key: key.toLocaleLowerCase(),
                            value: req.query[key]
                        };
                        ParamList.push(up);
                    }


                }
            }
            ParamList = ParamList.sort(function (o, p) {
                let a, b;
                if (typeof o === "object" && typeof p === "object" && o && p) {
                    a = o["key"];
                    b = p["key"];
                    if (a.toLocaleLowerCase() === b.toLocaleLowerCase()) {
                        return 0;
                    }
                    if (typeof a === typeof b) {
                        return a < b ? -1 : 1;
                    }
                    return typeof a < typeof b ? -1 : 1;
                }
            });
            let ParamVKStr = "" + MT;
            ParamList.forEach(function (item) {
                ParamVKStr += item.key + item.value;
            });
            let RVK = this.webTools.common.SHA1(ParamVKStr);
            if (VK !== RVK) {
                res.send(402, '参数验证失败');
            } else {
                next();
            }

        });

        //登录验证 权限过滤，无权访问的不能进入到下面的路由
        app.use(this.nameSpace, async  (req, res, next)=> {
            let isPass = false;

            this.UrlList.forEach((item) => {
                if (item.toLocaleLowerCase() === req.path.toLocaleLowerCase()) {
                    isPass = true;
                }
            });
            if (isPass) {
                next();
            } else {
                let UserInfo = jwt.verify(req.headers.token, this.config.authKeyWord);
               // let UserInfo = await this.curUserInfo.getUserInfo(req.headers.userid);
                if (!UserInfo || UserInfo.UserID === '' ) {
                    //res.json({Result:0,Msg:'用户登录鉴权失败'});
                    res.send(402, '用户登录鉴权失败');
                } else {
                    req.user = JSON.parse(JSON.stringify(UserInfo));
                    next();
                }

            }

        });

        //=======自动路由==按照目录结构进行路由=======
        this.autoUserRouter(this.nameSpace, app, __dirname + "/controls");
        //======= 自动路由 之后=========
        app.use(this.nameSpace, function (req, res) {
            let CB = {
                Result: 0,
                Msg: '404 page no find'
            };
            res.json(CB);
        });
    }
};
